package com.qz.mos.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetAddress;

@Slf4j
@Component
@Profile( "dev" )
public class MosApplicationRunner implements ApplicationRunner {


    @Autowired
    private TomcatServletWebServerFactory tomcatServletWebServerFactory;
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {

        this.showUrl();
        log.info("\n====================================================\n" +
                "配网模拟数据平台V1.0启动完成" +
                "\n====================================================\n");

        try {
//            jdbcTemplate.execute( "create alias regexp_like as \n" +
//                    "$$ boolean regexpLike(String s, String p) { return s.matches(p); } $$; " );

//            jdbcTemplate.execute( "create alias json_eq as\n" +
//                    " $$ boolean jsonEq(String s,String p) {\n" +
//                    "com.alibaba.fastjson.JSONObject jsonapp = com.alibaba.fastjson.JSON.parseObject(s);\n" +
//                    "com.alibaba.fastjson.JSONObject jsonp = com.alibaba.fastjson.JSON.parseObject(p);\n" +
//                    "return jsonapp.equals(jsonp);\n" +
//                    "}\n" +
//                    "$$" );
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    private void showUrl() throws Exception{
        String host = InetAddress.getLocalHost().getHostAddress();
        int port = tomcatServletWebServerFactory.getPort();
        String contextPath = tomcatServletWebServerFactory.getContextPath();
        String protocol = tomcatServletWebServerFactory.getSsl() != null ? "https://" : "http://";
        String address = protocol + host + ":" + port + contextPath+"/";
        log.info("欢迎访问:{}", address);
        log.info("数据库后台:{}", address + "h2");
        log.info("\n" +
                "数据库账号密码请查看配置文件" +
                "\n");
        openDefaultBrowser(address);

    }
    public static void openDefaultBrowser(String address){
        try {
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+address);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}